<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:bom:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:bom:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:bom:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:bom:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="产品" align="center" prop="wmsMaterialInfoList[0].name" />
      <el-table-column label="型号" align="center" prop="wmsMaterialInfoList[0].model" />
      <el-table-column label="规格" align="center" prop="wmsMaterialInfoList[0].specification" />
      <el-table-column label="单位" align="center" prop="wmsMaterialInfoList[0].unit" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:bom:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:bom:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品BOM单对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="bomRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="产品" prop="productId">
          <el-input v-model="form.wmsMaterialInfoListname" placeholder="" />
        </el-form-item>
        <el-divider content-position="center">BOM单明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddMesProductBomDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteMesProductBomDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="mesProductBomDetailList" :row-class-name="rowMesProductBomDetailIndex" @selection-change="handleMesProductBomDetailSelectionChange" ref="mesProductBomDetail">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="物料" align="center" prop="name" width="200">
            <template #default="scope">
              <div style="display: flex;"><el-input v-model="scope.row.name" placeholder="请选择物料" readonly />
                <el-button type="primary" @click="wxz=1,xz = true">选择</el-button></div>
            </template>
          </el-table-column>
          <el-table-column label="型号" prop="model" width="100"/>
          <el-table-column label="规格" prop="specification" width="100"/>
          <el-table-column label="单位" prop="unit" width="100"/>
          <el-table-column label="备注" prop="detailRemark" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.detailRemark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog id="el-dialog" v-model="xz" title="选择物料档案" width="1000">
    <div style="display: flex;">
      <el-tree style="max-width: 600px" :data="datatree" :props="defaultProps" :default-expand-all="true"
            @node-click="handleNodeClick" />
      <div>
        <div style="display: flex; justify-content: center;">
          <el-form-item label="物料编码" prop="code">
            <el-input v-model="form.code" placeholder="请输入物料编码" />
          </el-form-item>
          <el-form-item label="物料名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入物料名称" />
          </el-form-item>
        </div>
        <div style="display: flex;justify-content: center;">
          <el-form-item label="型号" prop="model">
            <el-input v-model="form.model" placeholder="请输入型号" />
          </el-form-item>
          <el-form-item label="规格" prop="sation">
            <el-input v-model="form.specification" placeholder="请输入规格" />
          </el-form-item>
        </div>
        <el-table @selection-change="handleSelectionChange" :data="wldata" style="width: 100%">
                <el-table-column property="id" label="编号" width="80" />
                <el-table-column property="code" label="物料编码" width="80" />
                <el-table-column property="name" label="物料名称" width="80" />
                <el-table-column property="model" label="型号" width="80" />
                <el-table-column property="specification" label="规格" width="100" />
                <el-table-column property="unit" label="单位" width="80" />
                <el-table-column property="price" label="单价" width="80" />
                <el-table-column property="type" label="类型" width="80" />
                <el-table-column property="remark" label="备注" width="50" />
                <el-table-column label="操作" width="80">
                    <template v-slot="scope">
                        <el-button @click="xzwl(scope.row,wxz), xz = false;" style="display: inline; width: 50px;">
                            选择
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
      </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Bom">
import { listBom, getBom, delBom, addBom, updateBom,wlseleid,selewl} from "@/api/system/bom";

const { proxy } = getCurrentInstance();

const bomList = ref([]);
const mesProductBomDetailList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedMesProductBomDetail = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const xz=ref(false);
const wldata=ref([]);
const datatree = [
    {
        label: '分类',
        children: [
            {
                label: '成品',
                children: [
                    {
                        label: '燃油车',
                    },
                    {
                        label: '新能源车'
                    }
                ],
            },
            {
                label: '零件',
                children: [
                    {
                        label: '发动机'
                    },
                    {
                        label: '变速箱'
                    },
                    {
                        label: '轮胎'
                    },
                    {
                        label: '电池'
                    },
                    {
                        label: '底盘'
                    },
                    {
                        label: '大灯'
                    },
                    {
                        label: '空调'
                    }, {
                        label: '座椅'
                    }
                ],
            }
        ],
    }
]
var code;
const data = reactive({
  form: {
      wmsMaterialInfoList: []
    },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
  },
  rules: {
    name: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询产品BOM单列表 */
function getList() {
  loading.value = true;
  listBom(queryParams.value).then(response => {
    bomList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    productId: null,
    description: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
  };
  mesProductBomDetailList.value = [];
  proxy.resetForm("bomRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加产品BOM单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getBom(_id).then(response => {
    form.value = response.data;
    form.value.wmsMaterialInfoListname=response.data.wmsMaterialInfoList[0].name
    mesProductBomDetailList.value = response.data.mesProductBomDetailList; 
    const oidDeta= mesProductBomDetailList.value 
    mesProductBomDetailList.value=[];
    for(var i=0;i<oidDeta.length;i++){
      console.log(oidDeta[i].materialId)
      wlseleid({id:oidDeta[i].materialId}).then(response => {
        mesProductBomDetailList.value.push(response[0])
      console.log(mesProductBomDetailList.value)
      console.log(response[0])
    })
    }
   
    open.value = true;
    title.value = "修改产品BOM单";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["bomRef"].validate(valid => {
    if (valid) {
      form.value.mesProductBomDetailList = mesProductBomDetailList.value;
      if (form.value.id != null) {
        updateBom(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBom(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除产品BOM单编号为"' + _ids + '"的数据项？').then(function() {
    return delBom(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** BOM单明细序号 */
function rowMesProductBomDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** BOM单明细添加按钮操作 */
function handleAddMesProductBomDetail() {
  let obj = {};
  obj.materialId = "";
  obj.usage = "";
  obj.remark = "";
  mesProductBomDetailList.value.push(obj);
}

/** BOM单明细删除按钮操作 */
function handleDeleteMesProductBomDetail() {
  if (checkedMesProductBomDetail.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的BOM单明细数据");
  } else {
    const mesProductBomDetails = mesProductBomDetailList.value;
    const checkedMesProductBomDetails = checkedMesProductBomDetail.value;
    mesProductBomDetailList.value = mesProductBomDetails.filter(function(item) {
      return checkedMesProductBomDetails.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleMesProductBomDetailSelectionChange(selection) {
  checkedMesProductBomDetail.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/bom/export', {
    ...queryParams.value
  }, `bom_${new Date().getTime()}.xlsx`)
}
const xzwl = (row,wl) => {
  if(wl!=1){
  form.value.name=row.name
  form.value.model=row.model
  form.value.specification=row.specification
  form.value.materialId=row.id
  }else{
    mesProductBomDetailList.value.pop()
    mesProductBomDetailList.value.push(row)
  }
}
function handleNodeClick(data) {
    // data 是当前节点的数据对象
    console.log(data.label);
    code = data.label
    wlsele()
}
function wlsele() {
    let applicant = ref({ id: form.id, name: form.name, model: form.model, specification: form.sation, code: code });
    const jsonString = JSON.stringify(applicant.value);
    console.log(jsonString)
    selewl(jsonString).then((response) => {

      wldata.value = response;
             for (var i = 0; i < response.length; i++) {
                 if (wldata.value[i].type == 1) {
                     wldata.value[i].type = "成品"
                 } else {
                     wldata.value[i].type = "原材料"
                 }
             }
    
  });
}
getList();
</script>
